package com.pingan.mobilegw.core.service.util;

import com.alibaba.common.lang.StringUtil;

import com.pingan.mobilegw.core.service.session.SessionConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 * 
 * @author jinwenxiang
 * @version $Id: CookieUtil.java, v 0.1 2013-11-21 下午8:27:37 jinwenxiang Exp $
 */
public class CookieUtil {

    private static Log logger = LogFactory.getLog(CookieUtil.class);

    /**
     * 通用的写cookie.
     */
    public static void writeCookie(String cookeName, String cookieValue,
                                   HttpServletResponse response) {
        Cookie cookie = new Cookie(cookeName, cookieValue);
        SessionConfig sessionConfig = SessionConfig.getConfig();
        String cookieDomain = sessionConfig.getSessionCookieDomain();
        if (StringUtil.isNotEmpty(cookieDomain)) {
            cookie.setDomain(cookieDomain);
        }
        int cookieMaxAge = sessionConfig.getSessionCookieMaxAge();
        if (cookieMaxAge > 0) {
            cookie.setMaxAge(cookieMaxAge);
        }
        cookie.setPath("/");
        if (logger.isDebugEnabled()) {
            logger.debug("Set cookie[committed=" + response.isCommitted() + ", length="
                         + StringUtil.defaultIfNull(cookie.getValue()).length() + "]: "
                         + cookie.getName() + "=" + StringUtil.defaultIfNull(cookie.getValue())
                         + "; domain=" + StringUtil.defaultIfNull(cookie.getDomain()) + "; path="
                         + StringUtil.defaultIfNull(cookie.getPath()));
        }
        response.addCookie(cookie);
    }
}
